#include <my_header.h>

/* Usage: ./11_client_epoll_断线重连 */
int main(void){                                  
    // 服务器的ip地址和端口
    char *ip = "192.168.229.128";
    char *port = "8080";

    // 创建socket对象
    int sofd = socket(AF_INET, SOCK_STREAM, 0);
    ERROR_CHECK(sofd, -1, "socket");

    // 创建struct sockaddr 类型
    struct sockaddr_in client_addr;
    client_addr.sin_family  = AF_INET;
    client_addr.sin_port = htons(atoi(port));
    client_addr.sin_addr.s_addr = inet_addr(ip);

    int res_conn = connect(sofd, (struct sockaddr *)&client_addr, sizeof(client_addr));
    ERROR_CHECK(res_conn, -1, "connect");

    // 创建epoll对象
    int epoll_fd = epoll_create(1);
    ERROR_CHECK(epoll_fd, -1, "epoll_create");
    // 设置监听集合
    struct epoll_event event;
    event.events = EPOLLIN;
    event.data.fd = STDIN_FILENO;
    int res_epoctl = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, STDIN_FILENO, &event);
    ERROR_CHECK(res_epoctl, -1, "epoll_ctl");

    event.data.fd = sofd;
    int res_epoctl2 = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sofd, &event);
    ERROR_CHECK(res_epoctl2, -1, "epoll_ctl");

    int flag = 0;
    while(1)
    {
        // 构建就绪接收数组
        struct epoll_event list[10];
        memset(list, 0, sizeof(list));
        int epoll_num = epoll_wait(epoll_fd, list, 10, -1);
        ERROR_CHECK(epoll_num, -1, "epoll_wait");
        
        // 遍历就绪集合
        for(int i =0; i<epoll_num; i++)
        {
            int fd = list[i].data.fd;

            if(fd == STDIN_FILENO)
            {
                char buf[60] = { 0 };
                read(STDIN_FILENO, buf, sizeof(buf));
                int res_send = send(sofd, buf, sizeof(buf), 0);
                ERROR_CHECK(res_send, -1, "send");
            }
            if(fd == sofd)
            {
                char buf[60] = {0 };
                ssize_t res_recv = recv(sofd, buf, sizeof(buf), 0);
                if(res_recv == 0)
                {
                    printf("client closed! \n");
                    flag = 1;
                    break;
                }
                printf("server message: %s\n", buf);
            }
        }
        if(flag != 0)
        {
            break;
        }

    }
    close(sofd);
    return 0;
}


